package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"log"
	"os"
	"path/filepath"
	"sync"
)

func fileMonitor(path map[string]int) {
	initWG := sync.WaitGroup{}
	initWG.Add(1)

	go func() {
		watcher, err := fsnotify.NewWatcher()
		if err != nil {
			log.Fatal(err)
		}
		defer watcher.Close()
		// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way

		eventsWG := sync.WaitGroup{}
		eventsWG.Add(1)
		go func() {
			for {
				select {
				case event, ok := <-watcher.Events:
					if !ok { // 'Events' channel is closed
						eventsWG.Done()
						return
					}
					fmt.Println(event.Name, event.Op.String())
					const writeOrCreateMask = fsnotify.Create | fsnotify.Write
					if event.Op&writeOrCreateMask != 0 {
						status := path[event.Name]
						fmt.Println(status)
						if status == 2 {
							eventsWG.Done()
							return
						}
					}

				case err, ok := <-watcher.Errors:
					if ok { // 'Errors' channel is not closed
						log.Printf("watcher error: %v\n", err)
					}
					eventsWG.Done()
					return
				}
			}
		}()

		for k := range path {
			filename := filepath.Clean(k)
			dir, _ := filepath.Split(filename)
			if _, err := os.Stat(dir); os.IsNotExist(err) {
				fmt.Println(dir, "not exist")
				os.MkdirAll(dir, 700)
			}
			fmt.Println("add to watcher", k)
			watcher.Add(dir)
		}

		// done initializing the watch in this go routine, so the parent routine can move on...
		initWG.Done()

		// now, wait for event loop to end in this go-routine...
		eventsWG.Wait()
	}()

	// make sure that the go routine above fully ended before returning
	initWG.Wait()
}

func main() {
	// Create new watcher.

	files := map[string]int {
		"config/a.yaml": 1,
		"bin/b.yaml": 2,
	}
	fmt.Println(files)
	fileMonitor(files)
	<-make(chan struct{})
}
